package com.wrial.mall.product.web.controller;
/*
 * @Author  Wrial
 * @Date Created in 15:51 2020/5/21
 * @Description
 */

import com.wrial.mall.product.entity.CategoryEntity;
import com.wrial.mall.product.service.CategoryService;
import com.wrial.mall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.redisson.client.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;
    @Autowired
    RedissonClient redisson;
    @Autowired
    StringRedisTemplate redisTemplate;

    @GetMapping(path = {"/", "/index.html"})
    public String index(Model model) {
        // TODO 查找出所有的一级分类
        List<CategoryEntity> categoryEntityList = categoryService.getLevel1Categorys();
        model.addAttribute("categorys", categoryEntityList);
        return "index";
    }

    @ResponseBody
    @GetMapping("/index/json/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        return categoryService.getCatalogJson();

    }

    /**
     * 最佳实践：lock.lock(30, TimeUnit.SECONDS)没看门狗续期机制，时间设置足够大就行
     * <p>
     * Redisson可以实现非公平/公平/tryLock
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/testLock")
    public String testLock() {
        // redis中根据uuid和线程完成的可重入锁
        // 而且在执行超长代码的时候会有看门狗来自动续约时间，保证业务正确进行，业务完成就不会给锁续期，即使不手动解锁，锁也会在默认的TTL（默认30s）后解锁
        RLock lock = redisson.getLock("my-lock");
        lock.lock();//阻塞式等待，无需自旋，如果是有参的lock就没有看门狗续期（1/3internalLockLeastTime，每次过1/3看门狗时间，就去续满时间）机制，这些底层都是通过Lua脚本来执行的
        System.out.println("获取锁成功，执行业务....." + Thread.currentThread().getId());
        try {
            System.out.println("释放锁" + Thread.currentThread().getId());
            Thread.sleep(3000); //模拟超长时间业务执行
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return "testLock";
    }


    /**
     * 在写为完成期间就不能读，多个读锁可以一起使用，写锁保证了数据的最新型（读锁期间可以写锁，但写期间不能读）
     *
     * @return
     */
    @GetMapping("/write")
    @ResponseBody
    public String writeLock() {
        String s = "";
        RReadWriteLock readWriteLock = redisson.getReadWriteLock("rw-lock");
        RLock rLock = readWriteLock.writeLock();
        try {
            rLock.lock();
            s = UUID.randomUUID().toString();
            Thread.sleep(20000);
            redisTemplate.opsForValue().set("writeValue", s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
        }

        return s;
    }

    @GetMapping("/read")
    @ResponseBody
    public String readLock() {
        RReadWriteLock readWriteLock = redisson.getReadWriteLock("rw-lock");
        RLock rLock = readWriteLock.readLock();
        String s = "";
        try {
            rLock.lock();
            Thread.sleep(20000);
            s = redisTemplate.opsForValue().get("writeValue");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
        }

        return s;
    }

    /**
     * 预先在redis设置park为3（或者调用几次go腾出位置），停三个车就不能再停了
     *
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/park")
    @ResponseBody
    public String park() throws InterruptedException {
        RSemaphore park = redisson.getSemaphore("park");
        park.acquire();
        return "ok";
    }

    @GetMapping("/go")
    @ResponseBody
    public String go() {
        RSemaphore park = redisson.getSemaphore("park");
        park.release();
        System.out.println("车位：" + redisTemplate.opsForValue().get("park"));
        return "ok";
    }

    /**
     * 闭锁，CountDownLatch
     *
     * @return
     * @throws InterruptedException
     */
    @GetMapping("lockDoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException {
        RCountDownLatch countDownLatch = redisson.getCountDownLatch("door");
        countDownLatch.trySetCount(3);// 设置count为3
        countDownLatch.await(); //等待闭锁的完成
        return "放假了，所有门都锁了！";
    }

    @GetMapping("gogogo/{id}")
    @ResponseBody
    public String gogogo(@PathVariable("id") Long id) {
        RCountDownLatch countDownLatch = redisson.getCountDownLatch("door");
        countDownLatch.countDown();  // 减一
        return id + "班的人走了";
    }
}
